<template>
  <div class="box">
    <el-card style="margin: 20px">
      <el-form :inline="true" class="demo-form-inline">
        <el-row>
          <el-col :span="8">
            <el-form-item label="标题">
              <el-input
                size="medium"
                placeholder="标题"
                v-model="searchForm.title"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8"
            ><el-form-item label="状态">
              <el-select
                v-model="searchForm.issueState"
                placeholder="请选择"
                style="width: 200px"
                size="medium "
              >
                <el-option label="全部" value=""></el-option>
                <el-option label="未发布" value="1"></el-option>
                <el-option label="已发布" value="2"></el-option>
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-button type="primary" size="medium " @click="search"
              >查询</el-button
            >
            <el-button type="primary" size="medium " @click="addNews"
              >添加通告</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card style="margin: 20px">
      <!-- 表格
        @selection-change="handleSelectionChange"
       -->
      <el-table
        ref="multipleTable"
        tooltip-effect="dark"
        style="width: 100%"
        stripe
        :data="list"
        border
        :header-cell-style="{ background: '#ebeef5' }"
      >
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column
          :prop="item.prop"
          v-for="(item, index) in tableList"
          :key="index"
          :label="item.label"
          :width="item.width"
        >
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button
              type="text"
              icon="el-icon-postcard"
              @click="issueNotice(row)"
              v-show="row.issueState == 1"
              >下发通知</el-button
            >
            <el-button type="text" icon="el-icon-edit" @click="editNews(row)"
              >编辑</el-button
            >
            <el-popconfirm
              title="确认删除这条通告吗？"
              @confirm="deleteNot(row)"
            >
              <el-button type="text" slot="reference" icon="el-icon-delete"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加与编辑弹窗 -->
      <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="77%"
        :before-close="handleClose"
      >
        <el-form
          label-width="400px"
          :model="formList"
          :rules="rules"
          ref="ruleFrom"
        >
          <el-form-item label="文章标题" prop="title">
            <el-input
              placeholder="请输入文章标题"
              v-model="formList.title"
              size="medium "
              style="width: 350px"
            ></el-input>
          </el-form-item>
          <el-form-item label="截止日期" prop="expirationDate">
            <el-date-picker
              size="medium "
              v-model="formList.expirationDate"
              style="width: 350px"
              type="datetime"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="文件" prop="fileName">
            <!-- 上传
              on-preview 点击已经上传的文件的钩子
              on-remove  删除已上传文件时的钩子
              before-remove 删除文件之前的钩子
              multiple 是否支持多选文件
              limit 上传文件数量
              on-exceed 文件超出个数限制时的钩子
              file-list 已上传文件的列表
              accept 上传文件的类型
             -->
            <el-upload
              class="upload-demo"
              action="/drug/file/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :on-success="onSuccess"
              multiple
              :limit="1"
              :on-exceed="handleExceed"
              accept=".doc,.txt,.pdf,.xls,.docx,.xlsx,.png,.jpg"
              :file-list="fileList"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <Editor
          v-model="formList.article"
          :value="formList.article"
          ref="editor"
        />
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 下发通知弹窗 -->
      <el-dialog
        title="选择下发机构"
        :visible.sync="dialogVisibleNotice"
        width="50%"
        :before-close="handleClose"
      >
        <div
          class="table"
          style="
            width: 100%;
            height: 3rem;
            display: flex;
            justify-content: space-around;
          "
        >
          <div class="tree">
            <div class="header">请选择下发机构</div>
            <div class="center">
              <el-tree
                :data="data"
                show-checkbox
                node-key="id"
                :props="defaultProps"
                @check="check"
              >
              </el-tree>
            </div>
          </div>
          <div class="tree">
            <div class="header">已选择{{ institutionList.length }}个机构</div>
            <div class="text">
              <div v-for="item in institutionList" :key="item.id">
                {{ item.deptName }}
              </div>
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleNotice = false">取 消</el-button>
          <el-button type="primary" @click="confirmation">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页器 -->
      <el-pagination
        style="margin-top: 20px; text-align: center"
        :current-page="page"
        :page-size="limit"
        :page-sizes="[8, 10, 15]"
        @current-change="getList"
        @size-change="handleSizeChange"
        layout="prev, pager, next,jumper,->,total,sizes "
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import { title } from "@/settings";
import { mapGetters } from "vuex";
export default {
  name: "",
  data() {
    return {
      // 展示数据
      fileList: [],
      // 数据列表
      list: [],
      // 表格列表
      tableList: [
        { prop: "title", label: "标题", width: "200" },
        { prop: "fileName", label: "文件名", width: "200" },
        { prop: "issuedNums", label: "下发单位数", width: "200" },
        { prop: "signInNums", label: "签收单位数", width: "200" },
      ],
      // 页数
      page: 1,
      // 展示数据条数
      limit: 8,
      // 数据条数
      total: 1,
      // 查询表单数据
      searchForm: {
        title: "",
        issueState: "",
      },
      // 弹框表单数据
      formList: {
        // 文章
        article: "",
        // 截止日期
        expirationDate: "",
        // 文件地址:
        file: "",
        // 文件名称
        fileName: "",
        // 标题
        title: "",
        // 作者
        author: "",
      },
      // 控制弹窗字段
      dialogVisible: false,
      dialogVisibleNotice: false,
      // 弹窗名
      title: "",
      // 树形控件数据
      data: [],
      defaultProps: {
        children: "deptList",
        label: "deptName",
      },
      // 选中的机构数据
      institutionList: [],
      // 表单校验
      rules: {
        title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
        expirationDate: [
          { required: true, message: "请选择截止时间", trigger: "blur" },
        ],
        fileName: [{ required: true, message: "请上传文件", trigger: "blur" }],
      },
      // 大队信息
      groupList: [],
      // 下发通知请求参数
      noticeList: {
        id: 0,
        informDepts: [],
      },
    };
  },
  mounted() {
    this.getList();
    this.getGroupList();
  },
  methods: {
    // 获取列表数据
    async getList(pager = 1) {
      this.page = pager;
      //解构vm的数据
      const { page, limit, searchForm } = this;
      let data = {
        pageNum: page,
        pageSize: limit,
        issueState: searchForm.issueState,
        title: searchForm.title,
      };
      let result = await this.$API.notificationd.reqGetList(data);
      if (result.status == 200) {
        this.list = result.data.records;
        this.total = result.data.total;
      }
    },
    // 获取机构信息
    async getGroupList() {
      let result = await this.$API.notificationd.reqGetGroupList();
      // 整理机构信息的数据
      if (result.status == 200) {
        this.data = result.data;
      }
    },
    // 查询按钮
    search() {
      this.getList();
    },
    // 当每页数据展示发生变化时的回调
    handleSizeChange(limit) {
      this.limit = limit;
      this.getList();
    },
    // 添加新闻按钮
    addNews() {
      this.dialogVisible = true;
      this.formList = {
        // 文章
        article: "",
        // 截止日期
        expirationDate: "",
        // 文件地址:
        file: "",
        // 文件名称
        fileName: "",
        // 标题
        title: "",
      };
      let editor = this.$refs.editor;
      console.log(editor);
      this.title = "新增新闻";
    },
    // 修改新闻按钮
    editNews(row) {
      this.formList = { ...row };
      let obj = {
        name: row.fileName,
        url: row.file,
      };
      this.fileList.push(obj);
      this.dialogVisible = true;
      this.title = "修改新闻";
    },
    // 弹窗确认按钮
    async confirm() {
      this.$refs.ruleFrom.validate(async (success) => {
        if (success) {
          this.formList.author = this.username;
          let result = await this.$API.notificationd.reqAddOrEdit(
            this.formList
          );
          if (result.status == 200) {
            this.$message({
              message: this.formList.id ? "修改成功" : "新增成功",
              type: "success",
            });
            this.dialogVisible = false;
            this.getList(this.formList.id ? this.page : 1);
            this.fileList = [];
          }
        } else {
          return false;
        }
      });
    },
    // 关闭弹窗的回调
    handleClose(done) {
      this.$confirm("您还未确认保存，确认退出吗？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 文件上传成功时的钩子
    onSuccess({ data }, file) {
      this.formList.fileName = file.name;
      this.formList.file = data.domain + data.path + "?download=0";
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      console.log(file, fileList);
      (this.formList.file = ""), (this.formList.fileName = "");
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file);
    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(`最多允许上传一个文件哦！`);
    },
    // 删除文件之前的钩子
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 下发通知按钮
    issueNotice(row) {
      this.noticeList.id = row.id;
      this.dialogVisibleNotice = true;
    },
    // tree复选框被勾选时发生的回调
    check(data, { checkedNodes }) {
      // console.log(data, { checkedNodes });
      this.institutionList = checkedNodes.filter((item) => {
        if (!item.deptList) {
          return item;
        }
      });
      console.log(this.institutionList);

      this.noticeList.informDepts = this.institutionList.map((item) => {
        return {
          deptId: item.id,
        };
      });
      console.log(this.noticeList.informDepts);
    },
    // 确认下发通知按钮
    async confirmation() {
      let result = await this.$API.notificationd.reqChange(this.noticeList);
      if (result.status == 200) {
        this.$message({
          message: "下发通知成功！",
          type: "success",
        });
        this.getList(this.page);
        this.dialogVisibleNotice = false;
      }
    },
    // 删除按钮
    async deleteNot(row) {
      let result = await this.$API.notificationd.reqDelete(row.id);
      if (result.status == 200) {
        // 当当前页删完，自动跳到上一页
        this.$message({
          message: "删除成功",
          type: "success",
        });
        this.getList(this.list.length > 1 ? this.page : this.page - 1);
      }
    },
  },
  // 计算属性
  computed: {
    // 计算用户名
    ...mapGetters(["username"]),
  },
};
</script>

<style lang="scss" scoped>
.tree {
  width: 40%;
  height: 3.3rem;
  border: 1px solid #dcdcdc;
  .header {
    width: 100%;
    height: 30px;
    text-align: center;
    line-height: 30px;
    background-color: #dcdcdc;
  }
  .text {
    width: 100%;
    height: 89%;
    color: #606266;
    text-align: center;
    overflow: auto;
    div {
      margin-top: 10px;
    }
  }
  .center {
    width: 100%;
    height: 88%;
    overflow: auto;
  }
}
</style>
